package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.BlogDao;
import model.Blog;
import model.User;
import utils.JSONUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/4/1 23:09
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    BlogDao blogDao = new BlogDao();
    /**
     * 获取所有博客列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String json;
        String blogIdParam = req.getParameter("blogId");
//        if (blogIdParam ==null || "".equals(blogIdParam)){
//            //博客列表
//            json = JSONUtils.toJSON(blogDao.selectAll());
//        }else {
//            //博客详情页
//            Integer blogId = Integer.parseInt(blogIdParam);
//            Blog blog = blogDao.getBlogByID(blogId);
//            json = JSONUtils.toJSON(blog);
//        }
        json = JSONUtils.toJSON(blogDao.selectAll());
        resp.getWriter().write(json);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title==null || "".equals(title) || content==null || "".equals(content)){
            resp.getWriter().write("文章标题或者内容为空");
            return;
        }
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("user") == null){
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user==null || user.getId()<=0){
            resp.getWriter().write("用户未登录");
            return;
        }
        Blog blog = new Blog();
        blog.setTitle(title).setContent(content).setUserId(user.getId());
        blogDao.insertBlog(blog);
        resp.sendRedirect("blog_list.html");
    }
}
